<template>
  <div class="login">
    <el-dialog
      title="登录"
      top="15vh"
      width="480px"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username" @keyup.enter.native="submitForm('ruleForm')"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            @keyup.enter.native="submitForm('ruleForm')"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.enter="submitForm('ruleForm')" :loading="loading">登录</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'login',
  data () {
    return {
      dialogVisible: true,
      loading: false,
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      ruleForm: {}
    }
  },
  methods: {
    submitForm (ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          this.loading = true
          this.$axios.post('/admin/login', this.ruleForm)
            .then(response => {
              this.loading = false
              if (response.data.err_code) {
                this.$message.warning(response.data.message)
              } else {
                // 登录成功
                this.$cookie.set('userinfo', JSON.stringify(response.data))
                this.$message({
                  type: 'success',
                  message: '登录成功',
                  duration: 1000,
                  onClose: () => {
                    window.location.href = '/'
                  }
                })
              }
            })
            .catch(() => {
              this.loading = false
              this.$message.error('系统错误')
            })
        }
      })

      return false
    }
  }
}
</script>

<style lang="stylus" scoped>
.login
  width 100%
  height 100vh
  background url("../assets/images/login_bg.jpg") no-repeat
  background-size cover
</style>
